package com.wmada.toolkit.ffmpeg.prop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wmada.toolkit.rpc.BufferedCmdParser;

/**
 * @author will.ma
 * @date 2020-11-3
 */
public class MediaInfoParser extends BufferedCmdParser<MediaInfo> {

    private MediaInfo info = null;

    @Override
    public MediaInfo getResult() {
        if (info == null) {
            info = parse();
        }
        return info;
    }

    private MediaInfo parse() {
        MediaInfo mediaInfo = new MediaInfo();

        String json = getOutput();

        JSONObject jsonObject = JSON.parseObject(json);
        JSONArray  jsonArray  = jsonObject.getJSONArray("streams");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject stream = jsonArray.getJSONObject(i);
            switch (stream.getString("codec_type").toLowerCase()) {
                case "video":
                    mediaInfo.addVideoInfo(VideoInfo.parse(stream));
                    break;
                case "audio":
                    mediaInfo.addAudioInfo(AudioInfo.parse(stream));
                    break;
                case "subtitle":
                    mediaInfo.addSubTitleInfo(SubTitleInfo.parse(stream));
                    break;
            }
        }
        return mediaInfo;
    }

}
